import { Browser } from 'puppeteer-core';
import * as fs from 'fs';
import * as path from 'path';

export interface Cookie {
  name: string;
  value: string;
  domain: string;
  path: string;
  expires: number;
  size: number;
  httpOnly: boolean;
  secure: boolean;
  session: boolean;
  sameSite?: string;
}

export class CookieManager {
  /**
   * 导出所有Cookie
   */
  static async exportCookies(browser: Browser, instanceId: string): Promise<Cookie[]> {
    try {
      const pages = await browser.pages();
      if (pages.length === 0) {
        console.warn('No pages available for cookie export');
        return [];
      }

      const page = pages[0];
      const client = await page.target().createCDPSession();
      
      // 获取所有Cookie
      const response = await client.send('Network.getAllCookies');
      const cookies = response.cookies || [];
      console.log(`Exported ${cookies.length} cookies for instance ${instanceId}`);
      return cookies;
    } catch (error) {
      console.error('Failed to export cookies:', error);
      return [];
    }
  }

  /**
   * 导入Cookie
   */
  static async importCookies(browser: Browser, cookies: Cookie[]): Promise<boolean> {
    try {
      const pages = await browser.pages();
      if (pages.length === 0) {
        throw new Error('No pages available');
      }

      const page = pages[0];
      const client = await page.target().createCDPSession();

      // 清除现有Cookie
      await client.send('Network.clearBrowserCookies');

      // 导入新Cookie
      for (const cookie of cookies) {
        const cookieData: any = {
          name: cookie.name,
          value: cookie.value,
          domain: cookie.domain,
          path: cookie.path,
          expires: cookie.expires,
          httpOnly: cookie.httpOnly,
          secure: cookie.secure
        };
        
        if (cookie.sameSite) {
          cookieData.sameSite = cookie.sameSite;
        }
        
        await client.send('Network.setCookie', cookieData);
      }

      return true;
    } catch (error) {
      console.error('Failed to import cookies:', error);
      return false;
    }
  }

  /**
   * 保存Cookie到文件
   */
  static saveCookiesToFile(cookies: Cookie[], filePath: string): void {
    try {
      const data = JSON.stringify(cookies, null, 2);
      fs.writeFileSync(filePath, data, 'utf8');
      console.log(`Cookies saved to: ${filePath}`);
    } catch (error) {
      console.error('Failed to save cookies to file:', error);
    }
  }

  /**
   * 从文件加载Cookie
   */
  static loadCookiesFromFile(filePath: string): Cookie[] {
    try {
      if (!fs.existsSync(filePath)) {
        return [];
      }
      const data = fs.readFileSync(filePath, 'utf8');
      return JSON.parse(data);
    } catch (error) {
      console.error('Failed to load cookies from file:', error);
      return [];
    }
  }

  /**
   * 获取Cookie文件路径
   */
  static getCookieFilePath(instanceId: string, basePath: string): string {
    return path.join(basePath, `${instanceId}_cookies.json`);
  }
} 